﻿using HtmlAgilityPack;
using Manhua2.Common;
using Manhua2.SQLiteTable;
using SharpCompress.Compressor;
using SharpCompress.Compressor.Deflate;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Manhua2.Helper;
namespace Manhua2.Provider
{
    public class BenGouProvider : IComicProvider
    {
        private const string provider = "bengou";

        private static DateTime lastUpdatedTime = DateTime.MinValue;

        public int TopCount { get { return 40; } }
        public string ProviderName
        {
            get { return provider; }
        } 

        public async Task SaveLatestComicsAsync(bool cache)
        {
            if (cache)
            {
                if ((DateTime.Now - lastUpdatedTime).TotalMinutes < 10)
                {
                    return;
                }
            }

            lastUpdatedTime = DateTime.Now;

            using (DbContext context = new DbContext())
            {
                context.BeginTransaction();

                try
                {
                    HtmlDocument html = await XHttpClient.GetHtmlDocumentAsync("http://www.bengou.com/update/list.html");

                    var lis = html.GetElementbyId("sa-comic_show_list").Element("ul").Elements("li");
                    foreach (var li in lis)
                    {
                        var div = li.Element("div");
                        var link = div.Element("a");
                        string title = link.Attributes["title"].Value.Trim();

                        var comic = await context.GetComic(title, this.ProviderName);
                        if (comic == null)
                        {
                            comic = new SQLiteComic();
                            comic.Provider = provider;

                            var cover = link.Element("img");

                            comic.Title = title;
                            comic.CoverUrl = cover.Attributes["src"].Value;
                            comic.ChapterUrl = link.Attributes["href"].Value;

                            await context.InsertAsync(comic);
                        }

                        var c = HtmlHelper.GetElementByClass(li, "chapter").FirstOrDefault();
                        var d = HtmlHelper.GetElementByClass(li, "date").FirstOrDefault();

                        DateTime dt;
                        if (!DateTime.TryParse(d.InnerText, out dt))
                            dt = DateTime.Now;

                        await context.InsertChapter(c.InnerText.Trim(), comic.Id, dt);
                    }

                    context.Commit();
                }
                catch
                {
                    context.Rollback();
                    throw;
                }
            }
        }

        public async Task SavePagesAsync(int chapterId)
        {
            using (DbContext context = new DbContext())
            {
                var chapter = await context.GetAsync<SQLiteChapter>(chapterId);
                if (chapter == null)
                    throw new ArgumentNullException("章节不存在");

                context.BeginTransaction();

                try
                {
                    HtmlDocument html = await XHttpClient.GetHtmlDocumentAsync(chapter.Url);
                    var match = Regex.Match(html.DocumentNode.InnerHtml,
                                            "var picTree = .*;");

                    if (!match.Success)
                        throw new ArgumentException("漫画加载失败");

                    string picTree = match.Value;
                    picTree = picTree.Substring(picTree.IndexOf('[') + 1);
                    picTree = picTree.Remove(picTree.LastIndexOf(']'));

                    match = Regex.Match(html.DocumentNode.InnerHtml,
                                        "var pic_base = '.*';");

                    if (!match.Success)
                        throw new ArgumentException("漫画加载失败");

                    string picBase = match.Value;
                    picBase = picBase.Substring(picBase.IndexOf('\'') + 1);
                    picBase = picBase.Remove(picBase.LastIndexOf('\''));

                    string[] pics = picTree.Split(',');
                    for (int i = 0; i < pics.Length; i++)
                    {
                        SQLitePage page = new SQLitePage();
                        page.ChapterId = chapter.Id;
                        page.Page = i + 1;
                        page.Url = picBase + pics[i].Trim('"');

                        await context.InsertAsync(page);
                    }

                    chapter.TotalPage = pics.Length;
                    await context.UpdateAsync(chapter);

                    context.Commit();
                }
                catch
                {
                    context.Rollback();
                    throw;
                }
            }
        }

        public async Task SaveChaptersAsync(int comicId)
        {
            using (DbContext context = new DbContext())
            {
                var comic = await context.GetAsync<SQLiteComic>(comicId);
                if (comic == null) throw new ArgumentNullException("comic");

                context.BeginTransaction();

                try
                {

                    HtmlDocument html = await XHttpClient.GetHtmlDocumentAsync(comic.ChapterUrl);

                    var info = HtmlHelper.GetElementByClass(html.DocumentNode, "cartoon-intro").FirstOrDefault();
                    if (info != null)
                    {
                        var div = info.Element("div");
                        comic.Author = div.Element("p").ChildNodes[1].InnerText;
                        await context.UpdateAsync(comic);
                    }

                    var links = (from p in HtmlHelper.GetElementByClass(html.DocumentNode, "hover")
                                 where p.Name == "span"
                                 select p).Reverse();

                    foreach (var link in links)
                    {
                        try
                        {
                            var a = link.Element("a");
                            if (a != null)
                            {
                                string title = a.Attributes["title"].Value.Trim();
                                string url = a.Attributes["href"].Value;

                                await context.InsertChapter(title, comic.Id, new DateTime(1970, 1, 1), url);
                            }
                        }
                        catch
                        {
                        }
                    }

                    context.Commit();
                }
                catch
                {
                    context.Rollback();
                    throw;
                }
            }
        }

        public override string ToString()
        {
            return provider;
        }
    }
}
